package store.lunangangster.engine.impl.bpmn.behavior;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import store.lunangangster.bpmn.model.FlowElement;
import store.lunangangster.bpmn.model.StartEvent;
import store.lunangangster.bpmn.model.SubProcess;
import store.lunangangster.engine.NodeFlowException;
import store.lunangangster.engine.impl.Context;
import store.lunangangster.engine.impl.entity.ExecutionEntity;

public class SubProcessBehavior extends ActivityBehavior {

  private static final Logger log = LoggerFactory.getLogger(SubProcessBehavior.class);

  @Override
  public void doBehavior(ExecutionEntity execution) {

    SubProcess subProcess = (SubProcess) execution.getCurrentFlowElement();
    log.info("SubProcess[\"{}\"]启动", subProcess);

    FlowElement startElement = null;
    for (FlowElement flowElement : subProcess.getFlowElements().values()) {
      if (flowElement instanceof StartEvent) {
        StartEvent startEvent = (StartEvent) flowElement;
        if (startEvent.getEventDefinitions() == null || startEvent.getEventDefinitions().isEmpty()) {
          startElement = startEvent;
          break;
        }
      }
    }

    if (startElement == null) {
      throw new NodeFlowException("子流程" + subProcess.getName() + "无启动事件");
    }

    ExecutionEntity subProcessExecution = Context.getProcessEngineConfiguration().getExecutionEntityManager()
        .createChildExecution(execution);

    // 转化为守护Execution，类似于ProcessInstance
    execution.setName(subProcess.getName());
    execution.setScope(true);

    subProcessExecution.setCurrentFlowElement(startElement);


    Context.getCommandContext().getAgenda()
        .addDoElementBehaviorOperation(subProcessExecution, null);
  }
}
